<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国活动断层数量'" />
          <ActiveFaultsNumber @showMap="showArc" :data="ActivityFaultData" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国危险性等级区划'" />
          <HazardLevelZoning :datas="NationwideRiskData" @levelClickVal="levelClickVal" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国建筑物分类统计'" />
          <DisasterBearingBodyData v-if="isChart" :listData="DisasterBodyData" @click="buildingClick" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国重点目标数据'" />
          <keyTargetData :listData="KeynoteTargetData" @targetClickVal="targetClickVal" @changeVal="changeVal" />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <headline :name="'全国地震灾害风险区划图'" />
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '-30px', left: '42px' }" />
          <OlMap :refId="'riskzonation'" style="height: 100%" @getMap="getMap" @mapClick="mapClick"></OlMap>
          <Legend :num2="num" :type="type" :typeName='typName' @optionSelected="optionSelected"></Legend>
          <!-- <select-legend
            style="position: absolute; left: 42px; bottom: 150px"
            :column1Title="'图例'"
            :column2Title="'设定烈度'"
            :column3Title="'四个概率水准'"
            :legendItems="legendItems"
            :options1="options1"
            :options2="options2"
            :defaultSelectedOption1="'2'"
            @optionSelected="handleOptionSelected"
          ></select-legend> -->
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国地震灾害风险评估'" />
          <RiskAssessmentData v-if="isData" :datas="RiskEstimateData" @clickRisk="riskAssessmentClick" :isShowChart="isShowChart"/>
          <!-- <RiskAssessmentData v-if="isData" :datas="RiskEstimateData" @click="riskAssessmentClick" :isShowChart="isShowChart"/> -->
        </div>
        <div class="app-right-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国地震地质灾害概况'" />
          <DisasterOverview v-if="isDatas" :datas="DisasterOverviewData" @titleClickVal="titleClickVal" />
        </div>

        <div class="app-right-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国地震灾害风险区划'" />

          <ZoningData v-if="isShow" :resultData="RiskPlanData" @riskClickVal="riskClickVal" />
        </div>
        <div class="app-right-item">
          <!-- 次级标题 -->
          <subheadings :name="'风险评估区划访问统计 '" />
          <RiskAccessStatistics />
        </div>
        <!-- <p class="chooseBox" @click="goSearch">
            <img src="../../assets/images/risk/choose.png" alt="" />
          </p> -->
        <!-- <div ref="chooseElement" class="chooseBox-bg" v-if="isShowRisk">
          <div class="assy">
            <div class="popup-head-x" @click="hidePopup()">X</div>
            <el-form>
              <el-form-item label="评估方式">
                <el-radio-group v-model="params.way" @change="getResult" class="radio1">
                  <el-radio v-for="(item, index) in statisticalOptions" :key="index" :label="item.value">
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="评估对象">
                <el-radio-group v-model="params.type" @change="getResult" class="radio1">
                  <el-radio v-for="(item, index) in Evaluation" :key="index" :label="item.value">
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="设定地震">
                <el-radio-group v-model="params.result" @change="getResult" class="radio1">
                  <el-radio v-for="(item, index) in scenarioEarthquake" :key="index" :label="item.value">
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <div class="searchBox">
              <p class="searchZoning">
                <span>区划</span>
              </p>
            </div>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>
<script setup>
// 系统选择
import SystemSelect from '@/components/SystemSelect';
import ActiveFaultsNumber from './components/ActiveFaultsNumber';
import HazardLevelZoning from './components/HazardLevelZoning';
import DisasterBearingBodyData from './components/DisasterBearingBodyData';
import keyTargetData from './components/KeyTargetData';
import RiskAssessmentData from './components/RiskAssessmentData';
import DisasterOverview from './components/DisasterOverview';
import ZoningData from './components/ZoningData';
import RiskAccessStatistics from './components/RiskAccessStatistics';
import {
  getActivityFaultData,
  getNationwideRiskData,
  getVisitNum,
  getRiskPlanData,
  getDisasterOverview,
  getRiskEstimateData,
  getKeynoteTargetData,
  getDisasterBodyData,
} from '@/api/riskZonation.js';
import { getfaultNum } from '@/api/activeFault.js';
// start
import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon, Text } from 'ol/style';
import Feature from 'ol/Feature';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';

import { GeoJSON as GeoJSonFormat } from 'ol/format';
// import SelectLegend from '@/components/SelectLegend';
import Legend from './components/Legend';
import { getChinaBaseMap, getChinaBaseFeature, getGridLayer, getBaseDir } from '@/map/projMap.js';
import { ArcgisService } from '@/map/ArcgisService';
import { Util } from '@supermap/iclient-ol';
import { getSqlTempLayer } from '@/utils/sqlTempLayersSet';
import { getResultLogisticGrowth } from '@/api/geologicalDisaster.js';
const isShowRisk = ref(false); //控制筛选盒子的显示与隐藏
const isShowChart =ref ('')
const data = reactive({
  params: {
    way: 2,
    type: 1, //评估对象
    result: 3, //设定地震
  },
  oriParams: {},
});
const { params, oriParams } = toRefs(data);
oriParams.value = JSON.parse(JSON.stringify(params.value));
const statisticalOptions = [
  { name: '确定评估', value: 1 },
  { name: '概率评估', value: 2 },
];
const Evaluation = [
  { name: '倒塌风险', value: 1 },
  { name: '人员伤亡', value: 2 },
  { name: '经济损失', value: 3 },
];
const scenarioEarthquake = [
  { name: 'VI度', value: 1 },
  { name: 'VII度', value: 2 },
  { name: 'VIII度', value: 3 },
  { name: 'IX度', value: 4 },
  { name: 'X度', value: 5 },
  { name: 'XI度', value: 6 },
];
// end
const ActivityFaultData = ref([]);
const NationwideRiskData = ref([]);
const VisitNumData = ref([]);

const RiskPlanObj = reactive({
  estimate0bj:'1',
  condition:'1',
  assessType:'1',
})

const DisasterOverviewData = ref([]);
const RiskEstimateData = ref({});
const KeynoteTargetData = ref([]);
const DisasterBodyData = ref([]);
const isShow = ref(false);
const isData = ref(false);
const isChart = ref(false);
const isDatas = ref(false);
// start
const mapInstance = ref(null);
const provinceLayer = ref(null);
const arcLayer = ref(null); //断层
const geologicalDisasterLandslipLayer = ref(null);
const geologicalDisasterSandyLayer = ref(null);
const geologicalDisasterSoftLayer = ref(null);
const levelLayer = ref(null);
const buildingLayer = ref(null);
const chinaBoundFeatures = ref(null);
const proviceFeatures = ref(null);
const changeTypeData = ref(['晚更新世断层', '早中更新世断层', '前第四纪断层', '全新世断层']);
const type = ref(1);
const num = ref(0);
const num4 = ref(0);
const injuryUrl = '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_casualties_calculation_ed_night_injure@fxfzfxqh';
const dieUrl = '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_casualties_calculation_ed_night_death@fxfzfxqh';
const lostUrl = '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_economic_loss_calculation_ed@fxfzfxqh';
const aseismaticUrls = [
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_kznl_1@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_kznl_2@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_kznl_3@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_kznl_4@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_kznl_5@fxfzfxqh',
];
const casualtiesUrls = [
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_1@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_2@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_3@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_4@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_5@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_1@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_2@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_3@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_4@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_rk_5@fxfzfxqh',
];
const financialLossUrls = [
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_1@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_2@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_3@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_4@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_5@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_1@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_2@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_3@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_4@fxfzfxqh',
  '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_assess_ed_qh_result_jj_5@fxfzfxqh',
];

watch(() => (RiskPlanObj),
  (newObj) => {
    getRiskPlanData({...newObj}).then((res) => {
    RiskPlanData.value = res.data;
  });
  }
);

// 全国危险性等级区划
async function levelClickVal(val) {
  await restProviceFeatures();
  console.log(val, '全国危险性等级区划');
  type.value = 7;
  if (!levelLayer.value) {
    let url = '/iserver/services/map-datacenter/rest/maps/jc_dangerous_levelm@datacenter';
    levelLayer.value = await getGridLayer(url);
    levelLayer.value.set('type', 7);
  }
  mapInstance.value.addLayer(levelLayer.value);
  setLayerVisiable();
}
// 全国建筑物分类统计
async function buildingClick() {
  await restProviceFeatures();
  type.value = 2;
  if (!buildingLayer.value) {
    let url = '/iserver/services/map-datacenter/rest/maps/jc_ds_gpb_gdzc_grid_total_housing@datacenter';
    buildingLayer.value = await getGridLayer(url);
    buildingLayer.value.set('type', 2);
  }
  mapInstance.value.addLayer(buildingLayer.value);
  setLayerVisiable();
}
const obj4 = {
  0: '学校',
  1: '医院',
  2: '生命线',
  3: '重大工程',
};
// 全国重点目标数据
async function targetClickVal(val) {
  await restProviceFeatures();
  console.log(val);
  type.value = 5;
  let promList = [];
  let url = '/iserver/services/map-fxfzfxqh/rest/maps/fxqh_keynote_target_data@fxfzfxqh';
  Object.keys(obj4).forEach((item) => {
    let name = obj4[item];
    let prom = new Promise(async (resolve, reject) => {
      let sqlText = `type='${name}'`;
      let layer = await getSqlTempLayer(url, sqlText);
      layer.set('type', 5);
      layer.set('num4', item);
      layer.setVisible(false);
      resolve(layer);
    });
    promList.push(prom);
  });
  Promise.all(promList).then((res) => {
    res.forEach((layer) => {
      mapInstance.value.addLayer(layer);
    });
  });
  getRiskLayerBySql(2, 1, 3, 5);
  setLayerVisiable();
}
//轮播图切换下标
function changeVal(val) {
  // console.log('轮询', val);
  num4.value = val;
  if (type.value == 5) {
    setLayerVisiable();
  }
}

//根据烈度类型获取大屏展示任务地震滑坡逻辑斯蒂计算结果并添加图层
const getResultLogisticGrowthByTYPE = async (dzIntensity) => {
  let res = await getResultLogisticGrowth(dzIntensity);
  console.log(res);
  let data = res.data?res.data:[];
  if (data && data.length > 0) {
    data.forEach((item) => {
      let taskId = item.taskId;
      let filePath = item.filePath;
      let url = '/iserver/services/map-demtif/rest/maps/' + filePath;
      let layerId = 'dzhp_level_' + dzIntensity + "_" + taskId;
      console.log(layerId+","+url);
      getGridLayer(url).then((layer) => {
        layer.setZIndex(2);
        layer.set('type', 3);
        layer.set('num2', num.value);
        geologicalDisasterLandslipLayer.value = layer;
      });
    });
  }
};

// 全国地震地址灾害概况
async function titleClickVal(val) {
  console.log(val);
  await restProviceFeatures();
  type.value = 3;
  if (val == '地震滑坡') {
    num.value = 1;
    if (!geologicalDisasterLandslipLayer.value) {
      /*let pack = process.env.NODE_ENV === 'development';
      let url = pack
        ? '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1692611889384_8'
        : '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1693795938950_8';
      let layer = null;
      try {
        layer = await getGridLayer(url);
        layer.setZIndex(2);
        layer.set('type', 3);
        layer.set('num2', num.value);
        geologicalDisasterLandslipLayer.value = layer;
      } catch (error) {
        console.log(error);
      }*/
      try {
        //根据烈度类型获取大屏展示任务地震滑坡逻辑斯蒂计算结果并添加图层（默认烈度8）
        getResultLogisticGrowthByTYPE(8);
      } catch (error) {
        console.log(error);
      }
      // let promList=[]
      // for (let i = 0; i < 5; i++) {
      //   let prom=getGridLayer(url+i)
      //   promList.push(prom)
      // }
      // Promise.all(promList).then(res={
      //   // res layer-list
      //   res.forEach(layer => {
      //     mapInstance.value.addLayer(layer)
      //   });
      // })
    }
    if (geologicalDisasterLandslipLayer.value) mapInstance.value.addLayer(geologicalDisasterLandslipLayer.value);
  } else if (val == '砂土液化') {
    num.value = 2;
    if (!geologicalDisasterSandyLayer.value) {
      //砂土液化图层，暂时有地震滑坡图层代替todo
      let pack = process.env.NODE_ENV === 'development';
      let url = pack
        ? '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1692611889384_8'
        : '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1693797282404_8';
      let layer = null;
      try {
        layer = await getGridLayer(url);
        layer.setZIndex(2);
        layer.set('type', 3);
        layer.set('num2', num.value);
        geologicalDisasterSandyLayer.value = layer;
      } catch (error) {
        console.log(error);
      }
    }
    if (geologicalDisasterSandyLayer.value) mapInstance.value.addLayer(geologicalDisasterSandyLayer.value);
  } else if (val == '软土震陷') {
    num.value = 3;
    if (!geologicalDisasterSoftLayer.value) {
      let url = '/iserver/services/map-fxfzdzzh/rest/maps/dzzh_soft_soil_polygon_evaluate_result@fxfzdzzh';
      let sqlText = "type =8'" + "' AND flag = '1'";
      let layer = null;
      try {
        layer = await getSqlTempLayer(url, sqlText);
        layer.setZIndex(2);
        layer.set('type', 3);
        layer.set('num2', num.value);
        geologicalDisasterSoftLayer.value = layer;
      } catch (error) {
        console.log('risk', error);
      }
    }
    if (geologicalDisasterSoftLayer.value) mapInstance.value.addLayer(geologicalDisasterSoftLayer.value);
  }
  setLayerVisiable(num.value);
}
//全国地震灾害风险区划
async function riskClickVal(val) {
  await restProviceFeatures();
  type.value = 1;
  let layers = mapInstance.value.getLayers();
  for (var i = layers.getLength() - 1; i >= 0; i--) {
    let layer = layers[i];
    if (layer?.get('type') && layer?.get('type') == 1) {
      mapInstance.value.removeLayer(layer);
    }
  }
  getRiskLayerBySql(2, 1, 3);
  setLayerVisiable();
}
const typName = ref('')
// 全国地震灾害风险评估
async function riskAssessmentClick(val) {
  await restProviceFeatures();
  type.value = 4;
  typName.value = val
  let injurySqlText = `del_flag='0'`; //todo:`del_flag='0' and '50年发生概率' and '轻微破坏'`
  let layer = await getSqlTempLayer(injuryUrl, injurySqlText);
  layer.set('type', 4);
  mapInstance.value.addLayer(layer);

  setLayerVisiable();
}
const getRiskLayerBySql = (way, type, result, num) => {
  let sqlText = `calculated_value<=10`;
  let promList = [];
  let urls = [];
  switch (way) {
    case 1:
      break;
    case 2:
      break;
  }
  switch (type) {
    case 1:
      sqlText += ` and estimate_obj='1'`;
      urls = aseismaticUrls;
      break;
    case 2:
      sqlText += ` and estimate_obj='2'`;
      urls = casualtiesUrls;
      break;
    case 3:
      sqlText += ` and estimate_obj='3'`;
      urls = financialLossUrls;
      break;
  }
  switch (result) {
    case 1:
      sqlText += ` and condition='ld1'`;
      break;
    case 2:
      sqlText += ` and condition='ld2'`;
      break;
    case 3:
      sqlText += ` and condition='ld3'`;
      break;
    case 4:
      sqlText += ` and condition='ld4'`;
      break;
    case 5:
      sqlText += ` and condition='ld5'`;
      break;
  }

  urls.forEach((url, index) => {
    let sqlTexts = '';
    if (type != 1) {
      if (index < 5) {
        sqlTexts = sqlText + ` and borderland_flag='0'`;
      } else {
        sqlTexts = sqlText + ` and borderland_flag='1'`;
      }
    }
    console.log('----sqlTexts--', sqlTexts);
    let prom = getSqlTempLayer(url, sqlTexts);
    promList.push(prom);
  });
  Promise.all(promList).then((res) => {
    res.forEach((layer) => {
      layer.setZIndex(1);
      layer.set('type', num ? 5 : 1);
      mapInstance.value.addLayer(layer);
      console.log('res---', layer);
    });
  });
};
// 点击筛选按钮
function goSearch() {
  isShowRisk.value = true;
}
function hidePopup() {
  isShowRisk.value = false;
}
function getResult() {}

// end
getData();
function getData() {
  // 全国活动断层数量
  getActivityFaultData().then((res) => {
    ActivityFaultData.value = res.data;
  });
  // 全国危险性等级区划
  getNationwideRiskData().then((res) => {
    NationwideRiskData.value = res.data;
  });
  //风险评估区划访问统计
  getVisitNum({ system: 1 }).then((res) => {
    VisitNumData.value = res.data;
  });
  //全国地震灾害风险区划
  getRiskPlanData({...RiskPlanObj}).then((res) => {
    RiskPlanData.value = res.data;
    isShow.value = true;
  });
  //全国地震地质灾害情况
  getDisasterOverview().then((res) => {
    DisasterOverviewData.value = res.data;
    isDatas.value = true;
  });
  //全国地震灾害风险评估
  getRiskEstimateData().then((res) => {
    RiskEstimateData.value = res.data;
    isData.value = true;
  });
  //全国重点目标数据
  getKeynoteTargetData().then((res) => {
    KeynoteTargetData.value = res.data;
  });
  //全国承灾体数据
  getDisasterBodyData().then((res) => {
    DisasterBodyData.value = res.data;
    isChart.value = true;
  });
}
const restProviceFeatures = () => {
  return new Promise((resolve, reject) => {
    if (proviceFeatures.value) {
      proviceFeatures.value.forEach((feature) => {
        feature.setStyle(
          new Style({
            fill: new Fill({ color: 'transparent' }),
            stroke: new Stroke({
              color: 'rgba(10, 22, 139, 1)',
              width: 0.5,
            }),
            text: new Text({
              font: '10px Calibri,sans-serif',
              fill: new Fill({ color: '#fff' }),
              text: feature.get('name'),
            }),
          })
        );
      });
    }
    resolve();
  });
};
const optionSelected = (params) => {
  console.log(params);
  isShowChart.value=params
  // 全国风险区划图数据-
  if (type.value == 1) {
    let { way, type, result } = params;
    let query = {
    estimate0bj:params.type,
    condition:params.result,
    assessType:params.way
  }
    getRiskLayerBySql(way, type, result);
    getRiskPlanData(query).then((res) => {
    RiskPlanData.value = res.data;
  });
  } else if (type.value == 4) {
    let url = '';
    let way = '';
    let type = '';
    let result = '';
    //全国风险评估
    switch (params.way) {
      case '人员受伤':
        url = injuryUrl;
        way = `del_flag='0'`;
        break;
      case '人员死亡':
        url = dieUrl;
        way = `del_flag='0'`;
        break;
      case '经济损失':
        url = lostUrl;
        way = `condition_type='11'`;
        break;
    }
    switch (params.type) {
      case '50年发生概率':
        type = '50年发生概率';
        break;
    }
    switch (params.result) {
      case '轻微破坏':
        result = '轻微破坏';
        break;
      case '中等破坏':
        result = '中等破坏';
        break;
      case '严重破坏':
        result = '严重破坏';
        break;
      case '毁坏':
        result = '毁坏';
        break;
    }
    let sqlText = `${way}`;
    console.log('sql---', sqlText);
    // let sqlText=`${way}' and type=${type} and result=${result}`
    requestRiskAssessmentLayer(url, sqlText);
  }
};
const requestRiskAssessmentLayer = async (url, sqlText) => {
  let layers = mapInstance.value.getLayers();
  for (var i = layers.getLength() - 1; i >= 0; i--) {
    let layer = layers[i];
    if (layer?.get('type') == 4) {
      mapInstance.value.removeLayer(layer);
    }
  }
  let layer = await getSqlTempLayer(url, sqlText);
  layer.set('type', 4);
  layer.setVisible(true);
  mapInstance.value.addLayer(layer);
};
const setLayerVisiable = (num2) => {
  let layers = mapInstance.value.getLayers();
  console.log('layers--', layers);
  for (var i = layers.getLength() - 1; i >= 0; i--) {
    let layer = layers.item(i);
    let ltype = layer?.get('type');
    if (ltype) {
      if (type.value == 3) {
        if (layer.get('num2') == num2) {
          layer.setVisible(true);
        } else {
          mapInstance.value.removeLayer(layer);
        }
      } else if (type.value == 5) {
        if (layer.get('num4')) {
          if (layer.get('num4') == num4.value) {
            layer.setVisible(true);
          } else {
            layer.setVisible(false);
          }
        } else if (ltype != 5) {
          mapInstance.value.removeLayer(layer);
        }
        // if (layer.get('num4') == num4.value) {
        //   layer.setVisible(true);
        // } else {
        //   mapInstance.value.removeLayer(layer);
        // }
      } else {
        if (ltype == type.value) {
          layer.setVisible(true);
        } else {
          mapInstance.value.removeLayer(layer);
        }
      }
    }
  }
};

const showArc = async () => {
  await restProviceFeatures();
  type.value = 6;
  getfaultNum().then((res) => {
    console.log('res--', res);
    let data = res.data;
    let data_0_50 = data[0];
    let data_50_150 = data[1];
    let data_150_300 = data[2];
    let data_300 = data[3];
    if (data_0_50 && data_0_50.length > 0) {
      setProvinceFaultLayer(0, data_0_50);
    }
    if (data_50_150 && data_50_150.length > 0) {
      setProvinceFaultLayer(1, data_50_150);
    }
    if (data_150_300 && data_150_300.length > 0) {
      setProvinceFaultLayer(2, data_150_300);
    }
    if (data_300 && data_300.length > 0) {
      setProvinceFaultLayer(3, data_300);
    }
    if (arcLayer.value) {
      mapInstance.value.addLayer(arcLayer.value);
      Util.setMask(arcLayer.value, chinaBoundFeatures.value[0]);
    }
    setLayerVisiable();
  });
};
const setProvinceFaultLayer = (type, data) => {
  if (proviceFeatures.value) {
    data.forEach((item) => {
      let feature = proviceFeatures.value.find((feature) => {
        if (feature.get('adcode') == item.code) {
          feature.set('faultNum', type);
          return feature;
        }
      });
      if (feature) {
        feature.setStyle(getProviceStyle(type, feature));
      }
    });
  }
};
const getProviceStyle = (type, feature) => {
  var color = {
    0: 'rgba(146, 160, 240, 1)',
    1: 'rgba(95, 133, 255, 1)',
    2: 'rgba(48, 96, 255, 1)',
    3: 'rgba(26, 66, 194, 1)',
  };
  return new Style({
    fill: new Fill({ color: color[type] }),
    stroke: new Stroke({ color: 'rgba(10, 22, 139, 1)', width: 0.5 }),
    text: new Text({
      font: '10px Calibri,sans-serif',
      fill: new Fill({ color: '#fff' }),
      text: feature.get('name'),
    }),
  });
};

const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);
  addChinaBound();
  addArcLayer();
  createProvinceLayer();
  // 默认显示全国地震灾害风险区划
  getRiskLayerBySql(2, 1, 3);
  // addProvinceNameLayer();
};
const mapClick = (event) => {
  const clickedFeature = mapInstance.value.forEachFeatureAtPixel(event.pixel, (feature) => feature);
  console.log('click', clickedFeature);
  return;
  if (clickedFeature) {
    // 获取点击的省份边界
    const provinceGeometry = clickedFeature.getGeometry();

    // 移除或隐藏其他省份图层
    mapInstance.value.getLayers().forEach((layer) => {
      // if (layer !== provinceLayer.value) {
      if (layer.get('id') !== 'province') {
        // mapInstance.value.removeLayer(layer);
        layer.setVisible(false);
      } else {
        console.log('layer---', layer.getSource().getFeatures());
        layer
          .getSource()
          .getFeatures()
          .forEach((feature) => {
            console.log('-----', clickedFeature.get('name'), feature.get('name'));
            if (clickedFeature.get('name') !== feature.get('name')) {
              feature.setStyle(null);
            }
          });
      }
    });
    // 创建新的省份图层并添加到地图
    const newProvinceLayer = new VectorLayer({
      source: new VectorSource({
        features: [new Feature(provinceGeometry)],
      }),
      zIndex: 2,
      style: new Style({
        stroke: new Stroke({
          color: 'blue',
          width: 2,
        }),
        // fill: new Fill({
        //   color: 'black',
        // }),
      }),
    });
    mapInstance.value.addLayer(newProvinceLayer);
    // 计算放大后的视图范围
    const provinceExtent = provinceGeometry.getExtent();
    // 更新地图视图以显示具体的省份地图
    mapInstance.value.getView().fit(provinceExtent, { padding: [20, 20, 20, 20], duration: 1000 }); // 1000毫秒的动画效果
  }
};
// 创建图层的函数
const createProvinceLayer = async () => {
  proviceFeatures.value = await getChinaBaseFeature();
  proviceFeatures.value.forEach((feature) => {
    feature.setStyle(
      new Style({
        fill: new Fill({ color: 'transparent' }),
        stroke: new Stroke({
          color: 'rgba(10, 22, 139, 1)',
          width: 0.5,
        }),
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
      })
    );
  });

  provinceLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 1,
    id: 'province',
  });
  provinceLayer.value.getSource().addFeatures(proviceFeatures.value);
  mapInstance.value.addLayer(provinceLayer.value);
};
const addChinaBound = () => {
  fetch(getBaseDir('China_4490.json'))
    .then((response) => response.json()) // 将响应解析为 JSON 数据
    .then((geojson) => {
      // 使用 GeoJSON 格式解析器将数据转换为 Features
      const geojsonFormat = new GeoJSonFormat();
      chinaBoundFeatures.value = geojsonFormat.readFeatures(geojson);
    })
    .catch((error) => {
      console.error('Error fetching or processing GeoJSON:', error);
    });
};
const addArcLayer = () => {
  let arcgisService = new ArcgisService({ map: mapInstance.value });
  let prom = arcgisService.showArcgisHddcLayerByName(changeTypeData.value, { key: 'type', value: '6' });
  prom.then((res) => {
    arcLayer.value = res.get('type');
    arcLayer.value.set('type', 6);
    // arcLayer.value.setVisible(false);
    // mapInstance.value.addLayer(arcLayer.value);
    // Util.setMask(arcLayer.value, chinaBoundFeatures.value[0]);
  });
};
// end
</script>

<style lang="scss" scoped>
.app-map {
  width: 960px;
  height: 100%;
  overflow: visible;
}
.app-main {
  display: flex;
  justify-content: space-between;
  .app-left {
    margin-left: 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    &-item {
      width: 450px;
      height: 170px;
      // background: linear-gradient(135deg, #00032D 0%, #000C58 50%, #00032D 100%);
      // opacity: .85;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      color: #fff;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
      &:nth-child(2) {
        height: 260px;
      }
      &:nth-child(3) {
        height: 260px;
      }
      &:nth-child(4) {
        height: 210px;
      }
    }
  }
  .app-right {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    position: relative;
    &-item {
      width: 450px;
      height: 220px;
      z-index: 10;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
      &:nth-child(2) {
        height: 280px;
        z-index: 10;
      }
      &:nth-child(3) {
        height: 220px;
        position: relative;
        z-index: 10;
      }
      &:nth-child(4) {
        height: 180px;
        z-index: 10;
      }
    }
  }
}
.chooseBox {
  position: absolute;
  right: 150px;
  top: 15px;
  cursor: pointer;
}
.chooseBox-bg {
  width: 420px;
  margin: -30px 0 0 10px;
  height: 350px;
  /* background: linear-gradient(NaNdeg, rgba(5, 12, 53, 0.8) 0%, rgba(4, 16, 89, 0.8) 55%, rgba(6, 40, 150, 0.8) 100%); */
  background: rgba(6, 40, 150, 0.8);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 2px solid #0190f9;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: absolute;
  bottom: 0px;
  z-index: 99;
}
.assy {
  color: #fff;
  padding: 0 20px;
  position: relative;
  .popup-head-x {
    position: absolute;
    right: 20px;
    top: 10px;
    font-size: 16px;
    cursor: pointer;
    z-index: 1000;
  }
  label {
    font-weight: 400;
  }
  .el-form-item {
    display: block;
    font-size: 18px;
    position: relative;
    padding-left: 8px;
    margin-bottom: 5px;
    &::before {
      content: '';
      display: block;
      width: 3px;
      height: 15px;
      background: #fff;
      position: absolute;
      top: 8px;
      left: 0;
    }
    :deep(.el-form-item__label) {
      display: block;
      color: #fff;
      font-size: 18px;
      font-weight: 400;
      text-align: left;
    }
    &:last-child {
      &::before {
        display: none;
      }
    }
    .el-radio {
      margin: 4px 0;
      padding-left: 12px;
      color: #fff;
      font-size: 18px;
    }
    .radio1 {
      display: flex;
      width: 100%;
      .el-radio {
        width: calc(100% / 3);
      }
    }
    .radio2 {
      display: flex;
      flex-wrap: wrap;
      .el-radio {
        width: 50%;
        margin: 3px 0;
      }
    }
  }

  :deep(.el-slider) {
    width: 370px;
    margin: 24px auto 10px;
    .el-slider__runway {
      height: 20px;
      // background: linear-gradient(#1D388F 0%, #0B1864 53%, #1D388F 100%);
      background: #000535;
      border-radius: 0;
      opacity: 1;
      border: 1px solid #46ffff;

      .el-slider__bar {
        margin: 0 10px 0 3px;
        top: 5px;
        height: 10px;
        background: url('@/assets/images/intensity/slider-bar.png') repeat-x;
      }

      .el-slider__button-wrapper {
        top: 0;
        height: 100%;

        .el-slider__button {
          margin-top: -7px;
          margin-left: 8px;
          width: 17px;
          height: 34px;
          background: url('@/assets/images/disaterLosses/slider-arrow.png') no-repeat center;
          background-size: 100% 100%;
          border: none;
          border-radius: 0;
          margin-bottom: -2px;
        }
      }
    }

    .el-slider__marks {
      .el-slider__marks-text {
        margin-top: -28px;
        color: #dffaff;
        font-size: 18px;
      }
    }

    .el-slider__stop {
      display: none;
    }
  }
  .searchBox {
    width: 100%;
    display: flex;
    justify-content: right;
  }
  .searchZoning {
    width: 60px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #46ffff;
    span {
      width: 32px;
      height: 16px;
      font-size: 16px;
      font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      font-weight: 400;
      color: #46ffff;
      line-height: 14px;
      -webkit-text-stroke: 1px rgba(0, 0, 0, 0);
    }
  }
}
</style>
